<template>
  <view class="index">
<!--    菜单栏
    <view class="cart-menu-box">
      <view class="cart-menu">
        <text class="cart-count">全部<text class="num">{{ total }}</text></text>
      </view>
      <view class="cart-menu">
        <text class="cart-menu-info">降价<text class="num">0</text></text>
      </view>
      <view class="cart-menu">
        <text class="cart-menu-info">筛选</text>
      </view>
    </view> -->

    <!-- 商品列表 -->
    <view class="cart-box">
      <view
        v-for="(item, index) in cartList"
        :key="item.id"
        class="cart-info-box"
      >
        <!-- 选择框 -->
        <view class="cart-check-box">
          <checkbox
            class="cart-check"
            :checked="selected[index]"
            @tap="toggleSelect(index)"
          />
        </view>

        <!-- 商品信息 -->
        <view class="cart-info">
          <image
            class="cart-image"
            :src="item.image"
            mode="aspectFill"
          ></image>
          <view class="cart-info-detail">
            <text class="goods-name">{{ item.name }}</text>
            <text class="cart-price">￥{{ item.price.toFixed(2) }}</text>

            <!-- 数量控制 -->
            <view class="cart-action-box">
              <button class="cart-action-btn" @click.stop="decrease(index)">-</button>
              <text class="cart-action-num">{{ item.num }}</text>
              <button class="cart-action-btn" @click.stop="increase(index)">+</button>
            </view>
          </view>
        </view>
      </view>

      <view class="blank-box"></view>
    </view>

    <!-- 结算栏 -->
    <view class="settle-box">
      <checkbox
        class="check-all"
        :checked="isAllSelected"
        @tap="toggleSelectAll"
      >全选</checkbox>

      <text class="cart-price-box">
        合计：<text class="total-price">{{ totalPrice.toFixed(2) }}</text>元
      </text>

      <text class="del-checked" @click="removeSelected">删除</text>

      <button class="settle-btn" @tap="goToSettlement">去结算</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { onShow, onLoad, onUnload } from '@dcloudio/uni-app'
import userManager from '@/common/utils/user.js'
import { getShoppingCartList,updateCartQuantity,deleteCartItems,createOrder  } from '@/api/Productapi.js'

// 购物车商品列表
const cartList = reactive([])

// 每个商品的选中状态（用索引对应）
const selected = reactive([])

// 保存原始数量（用于对比是否修改）
const originalNumMap = reactive({}) // key: cartId, value: original num

// 总数
const total = ref(0)

// 后端商品模板（仅作参考，实际从接口获取）
// const productInfo = ref({
//   id: null,
//   name: '',
//   price: null,
//   originalPrice: null,
//   image: '',
//   description: '',
//   sales: null,
//   stock: null,
//   rating: null
// })

// === 计算属性：总价 ===
const totalPrice = computed(() => {
  return cartList.reduce((sum, item, idx) => {
    return selected[idx] ? sum + item.price * item.num : sum
  }, 0)
})

// === 计算属性：是否全选 ===
const isAllSelected = computed(() => {
  return cartList.length > 0 && selected.every(Boolean)
})

// === 获取购物车数据 ===
const loadCartData = async () => {
  // 检查用户是否登录
  const user = userManager.user;
  if (!user || !user.userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }

  const userId = user.userId;

  uni.showLoading({ title: '加载中...' });

  try {
    const cartItems = await getShoppingCartList(userId);

    // 清空现有数据
    cartList.length = 0;
    selected.length = 0;
	Object.keys(originalNumMap).forEach(key => delete originalNumMap[key]);

    cartItems.forEach(item => {
      cartList.push({
        id: item.id,
        cartId: item.cartId,
        name: item.name,
        price: item.price,
        image: item.image,
        num: item.num,
        stock: item.stock,
        productId: item.productId
      });
      // 注意：这里 selected 是根据后端 selected 字段恢复状态
      selected.push(item.selected);
	  // 保存原始数量
	  originalNumMap[item.cartId] = item.num;
    });

    total.value = cartList.length;

  } catch (error) {
    console.error('加载购物车失败:', error);
    uni.showToast({ title: '加载失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
}

// === 切换单个选择 ===
const toggleSelect = (index) => {
  selected[index] = !selected[index]
}

// === 全选/取消全选 ===
const toggleSelectAll = () => {
  const newValue = !isAllSelected.value
  selected.forEach((_, i) => {
    selected[i] = newValue
  })
}

// === 减少数量 ===
const decrease = (index) => {
  if (cartList[index].num > 1) {
    cartList[index].num--
  }
}

// === 增加数量 ===
const increase = (index) => {
  // cartList[index].num++
  // 可加库存判断
    if (cartList[index].num < cartList[index].stock) {
      cartList[index].num++;
    } else {
      uni.showToast({ title: '已达库存上限', icon: 'none' });
    }
}

// === 批量保存数量变更到后端 ===
const saveCartQuantityChanges = async () => {
  const user = userManager.user;
  if (!user || !user.userId) return;

  const updates = [];

  cartList.forEach(item => {
    const original = originalNumMap[item.cartId];
    if (original !== undefined && item.num !== original) {
      updates.push({
        cartId: item.cartId,
        num: item.num
      });
      // 更新原始值，避免重复提交
      originalNumMap[item.cartId] = item.num;
    }
  });

  if (updates.length === 0) return;

  try {
    await updateCartQuantity(user.userId, updates); 
  } catch (error) {
    console.error('保存购物车数量失败:', error);
    uni.showToast({ title: '保存失败，请重试', icon: 'none' });
	// 回滚到原始数量
	  cartList.forEach(item => {
	    if (originalNumMap[item.cartId] !== undefined) {
	      item.num = originalNumMap[item.cartId];
	    }
	  });
  }
}


// === 删除已选商品 ===
const removeSelected = async () => {
  const user = userManager.user;
  if (!user || !user.userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }

  // 获取选中的 cartId 列表
  const selectedCartIds = [];
  const indicesToRemove = [];

  cartList.forEach((item, index) => {
    if (selected[index]) {
      selectedCartIds.push(item.cartId);
      indicesToRemove.push(index);
    }
  });

  if (selectedCartIds.length === 0) {
    uni.showToast({ title: '请先选择要删除的商品', icon: 'none' });
    return;
  }

  uni.showLoading({ title: '删除中...' });

  try {
    // 调用后端接口删除
    const success = await deleteCartItems(user.userId, selectedCartIds);
    if (success) {
      // 从本地移除（逆序删除避免索引错乱）
      indicesToRemove.sort((a, b) => b - a).forEach(index => {
        cartList.splice(index, 1);
        selected.splice(index, 1);
      });
      total.value = cartList.length;
      uni.showToast({ title: '删除成功', icon: 'success' });
    } else {
      uni.showToast({ title: '删除失败', icon: 'none' });
    }
  } catch (error) {
    console.error('删除异常:', error);
    uni.showToast({ title: '删除出错', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// === 去结算 ===
const goToSettlement = async () => {
	const user = userManager.user;
	  if (!user || !user.userId) {
	    uni.showToast({ title: '请先登录', icon: 'none' });
	    return;
	  }
	// 先保存购物车选择的数量变更
	await saveCartQuantityChanges();
	
  const checkedItems = cartList.filter((_, i) => selected[i])
  console.log("checkedItems:",checkedItems);
  if (checkedItems.length === 0) {
    uni.showToast({ title: '请先选择商品', icon: 'none' })
    return
  }
	
	
  uni.navigateTo({
    url: '/pages/confirm/confirm?carts=' + encodeURIComponent(JSON.stringify(checkedItems))
  })
}

// === 页面卸载时保存（如返回上一页）===
onUnload(() => {
  saveCartQuantityChanges();
});

// 页面显示时加载数据
onShow(() => {
  loadCartData()
})
</script>

<style scoped>
.index {
  background-color: #f9f9f9;
  min-height: 100vh;
}

/* 菜单栏 */
.cart-menu-box {
  width: 100%;
  height: 80rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  font-size: 28rpx;
  color: #333;
}

.cart-menu {
  flex: 1;
  text-align: center;
  line-height: 80rpx;
  position: relative;
}

.cart-count, .cart-menu-info {
  font-weight: bold;
}

.cart-count {
  color: #e64340;
}

.num {
  margin-left: 6rpx;
  padding: 0 12rpx;
  background-color: #ffebee;
  color: #e64340;
  border-radius: 12rpx;
  font-size: 24rpx;
  line-height: 32rpx;
}

/* 商品列表 */
.cart-box {
  margin-bottom: 100rpx;
}

.cart-info-box {
  width: 94%;
  height: 220rpx;
  margin: 20rpx auto 10rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  overflow: hidden;
}

.cart-check-box {
  width: 12%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-check {
  transform: scale(0.7);
}

.cart-info {
  width: 88%;
  display: flex;
}

.cart-image {
  width: 180rpx;
  height: 180rpx;
  margin: 20rpx 10rpx;
  border-radius: 20rpx;
  object-fit: cover;
}

.cart-info-detail {
  flex: 1;
  padding: 20rpx 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 40rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cart-price {
  font-size: 30rpx;
  color: #e64340;
  font-weight: bold;
}

.cart-action-box {
  display: flex;
  align-items: center;
}

.cart-action-btn {
  width: 60rpx;
  height: 50rpx;
  font-size: 34rpx;
  background-color: #f5f5f5;
  border: none;
  border-radius: 8rpx;
  margin: 0 10rpx;
  color: #333;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-action-btn::after {
  border: none;
}

.cart-action-num {
  width: 100rpx;
  height: 50rpx;
  line-height: 50rpx;
  text-align: center;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.blank-box {
  height: 40rpx;
}

/* 结算栏 */
.settle-box {
  width: 100%;
  height: 100rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
}

.check-all {
  transform: scale(0.8);
}

.cart-price-box {
  font-size: 28rpx;
  color: #333;
  margin-left: 20rpx;
}

.total-price {
  color: #e64340;
  font-weight: bold;
}

.del-checked {
  font-size: 28rpx;
  color: #1e90ff;
  text-decoration: underline;
  margin-left: 30rpx;
}

.settle-btn {
  width: 200rpx;
  height: 80rpx;
  font-size: 32rpx;
  background-color: #e64340;
  color: #fff;
  border-radius: 40rpx;
  margin-left: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}
</style>